package com.paipaideli.ui.home;

import android.content.Context;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.airbnb.epoxy.EpoxyAdapter;
import com.airbnb.epoxy.EpoxyHolder;
import com.airbnb.epoxy.EpoxyModelWithHolder;
import com.jakewharton.rxbinding2.view.RxView;
import com.paipaideli.R;
import com.paipaideli.common.base.BasePresenterFragment;
import com.paipaideli.common.http.Api;
import com.paipaideli.common.pullrefresh.PullRefreshView;
import com.paipaideli.common.utils.DateUtil;
import com.paipaideli.common.utils.ImageUtil;
import com.paipaideli.common.utils.ToastUtil;
import com.paipaideli.common.utils.preferrnces.FastData;
import com.paipaideli.common.views.DownTextView;
import com.paipaideli.ui.home.adapter.HomePageItemDecoration;
import com.paipaideli.ui.home.adapter.model.GoodsView;
import com.paipaideli.ui.home.bean.ProductListBean;
import com.paipaideli.ui.product.ProductDetailActivity;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class LotsFragment extends BasePresenterFragment {

    Unbinder unbinder;
    @BindView(R.id.recycleview_lots)
    PullRefreshView recycleview_lots;
    @BindView(R.id.top_back)
    RelativeLayout top_back;
    @BindView(R.id.top_title)
    TextView top_title;
    @BindView(R.id.tablayout)
    TabLayout mTabLayout;

    private LotsAdapter lotsAdapter;

    private String toDayTimer;
    private String toHDayTimer;
    private String TimeDay;

    private long startTime;
    private long endTime;
    private long nowTime;

    public static LotsFragment newInstance() {
        LotsFragment fragment = new LotsFragment();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_lots, container, false);
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    List<String> listTime = new ArrayList<>();

    //获取天数
    private List<String> day() {
        int year = currentYear();
        int month = currentMonth();
        int currentDay = currentDay();
        List<String> listDay = new ArrayList<>();
        listDay.add("今天");//year+month+day
        toDayTimer = year + "-" + month + "-" + currentDay;
        listTime.add(toDayTimer);

        int day = getDay(year, month);
        int mMonth = 0;
        int mDay = currentDay;
        int mYear = year;

        if (currentDay == day && month < 12) {//判断是每月的最后一天
            mMonth = month + 1;
            mDay = 1;
        } else if (currentDay == day && month == 12) { //判断是一年的最后一天
            mMonth = 1;
            mDay = 1;
            mYear = mYear + 1;
        } else {
            mMonth = month;
            mDay = currentDay + 1;
        }

        String toMDayTimer = mYear + "-" + mMonth + "-" + mDay;
        listTime.add(toMDayTimer);
        listDay.add(mMonth + "月" + mDay + "日");


        int hMonth = 0;
        int hDay = currentDay;
        int hYear = year;

        if (currentDay == day && month < 12) {//判断是每月的最后一天 后天就是为2号
            hMonth = month + 1;
            hDay = 2;
        } else if (currentDay == day && month == 12) { //判断是一年的最后一天 后天就是下一年的2号
            hMonth = 1;
            hDay = 2;
            hYear = hYear + 1;
        } else if (currentDay <= day - 2) { //当前日期小于等于当月天数 - 2
            hMonth = month;
            hDay = currentDay + 2;
        } else {    //每个月最后一天的前一天
            hMonth = month + 1;
            hDay = 1;
            if (month == 12) {
                hYear = hYear + 1;
                hMonth = 1;
            }
        }

        toHDayTimer = hYear + "-" + hMonth + "-" + hDay;
        listTime.add(toHDayTimer);
        listDay.add(hMonth + "月" + hDay + "号");

        System.out.printf(listDay.toString());
        System.out.printf(listTime.toString());
        return listDay;
    }

    //获取天数
    private int getDay(int year, int month) {
        int day = 30;
        boolean flag = false;
        switch (year % 4) {
            case 0:
                flag = true;
                break;
            default:
                flag = false;
                break;
        }
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                day = 31;
                break;
            case 2:
                day = flag ? 29 : 28;
                break;
            default:
                day = 30;
                break;
        }
        return day;
    }


    private int currentYear() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.YEAR);
    }

    private int currentMonth() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.MONTH) + 1;
    }

    private int currentDay() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.DAY_OF_MONTH);
    }


    @Override
    public void initView() {
        top_back.setVisibility(View.GONE);
        top_title.setText("拍品");

        for (int i = 0; i < day().size(); i++) {
            TabLayout.Tab tab = mTabLayout.newTab();
            tab.setTag(i);
            tab.setText(day().get(i));
            mTabLayout.addTab(tab);
        }

        recycleview_lots.setEnableRefresh(true);
        //设置是否在全部加载结束之后Footer跟随内容
        recycleview_lots.setOnRefreshListener(refreshlayout -> {
            lotsAdapter.clear();
            initDate();
            recycleview_lots.finishRefresh();
        });

        lotsAdapter = new LotsAdapter();
        recycleview_lots.addItemDecoration(new HomePageItemDecoration(10));
        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 2);
        recycleview_lots.setLayoutManager(layoutManager);
        recycleview_lots.setAdapter(lotsAdapter);

        TimeDay = listTime.get(0);
        recycleview_lots.showLoading();
        initDate();

        //设置tab的点击监听器
        mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                TimeDay = listTime.get(tab.getPosition());

                lotsAdapter.clear();
                initDate();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

//    @Override
//    public void onHiddenChanged(boolean hidden) {
//        super.onHiddenChanged(hidden);
//        if(!hidden){
//            System.gc();
//            lotsAdapter.clear();
//            lotsAdapter.notifyDataSetChanged();
//            initDate();
//        }
//    }

    public void initDate() {
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("dataTime", TimeDay);
            requestData.put("pageSize", "100");
        } catch (Exception e) {
            e.getMessage();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().list(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    recycleview_lots.finishLoading();
                    if (request.code.equals("200")) {
                        if (request.data.size() == 0) {
                            lotsAdapter.clear();
                            lotsAdapter.notifyDataSetChanged();
                            recycleview_lots.showEmpty(request.msg);
                            return;
                        }
                        lotsAdapter.setList(request.data);
                        lotsAdapter.notifyDataSetChanged();
                    } else {
                        recycleview_lots.showEmpty(request.msg);
                        ToastUtil.show(request.msg);
                    }
                }, throwable -> {
                    recycleview_lots.finishLoading();
                    recycleview_lots.showError(throwable);
                    Log.e(TAG, "error", throwable);
                });
    }


    public class LotsAdapter extends EpoxyAdapter {

        void setList(List<ProductListBean.Data> list) {
            for (int i = 0; i < list.size(); i++) {
                GoodsViewHolder goodsViewHolder = new GoodsViewHolder();
                goodsViewHolder.setData(list.get(i));
                models.add(goodsViewHolder);
            }
            Log.e("msgList", list.size()+"");
        }

        void clear() {
            models.clear();
        }

        //首页拍品数据
        public class GoodsViewHolder extends EpoxyModelWithHolder<GoodsViewHolder.ViewHolder> {
            ProductListBean.Data data;

            public void setData(ProductListBean.Data data) {
                this.data = data;
            }

            private int itemWidth = (getScreenRect().width() - 50) / 2;
            private ViewGroup.LayoutParams layoutParams;

            @Override
            protected ViewHolder createNewHolder() {
                return new ViewHolder();
            }

            @Override
            public void bind(@NonNull ViewHolder viewHolders) {
                super.bind(viewHolders);
                ImageUtil.displayImage(data.coverImgPath, viewHolders.imageLotsPhoto);
                viewHolders.tvLotsTitle.setText(data.goodsName);
                viewHolders.tvLotsPrice.setText("￥" + data.goodsStartingPrice);
                viewHolders.tvLotsScprice.setText("￥" + data.goodsMarketPrice);
                layoutParams = viewHolders.imageLotsPhoto.getLayoutParams();
                layoutParams.width = itemWidth;
                layoutParams.height = itemWidth;
                nowTime = DateUtil.getCurTimeLong();
                startTime = data.startTime;
                endTime = data.endTime;

                //将前一个缓存清除
                if (viewHolders.tvLotsCountDown != null) {
                    viewHolders.tvLotsCountDown.cancel();
                }
                viewHolders.tvItemBg.setVisibility(View.GONE);
                if (startTime - nowTime > 0) {//拍场未开始
                    viewHolders.tvLotsCountDown.init(startTime - nowTime, endTime - startTime, 0, new DownTextView.CouponDownInterface() {
                        @Override
                        public void runDown() {
                            viewHolders.tvItemBg.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void runText(long timer, int type) {

                        }
                    });
                } else if (startTime - nowTime < 0 && endTime - nowTime > 0) {//拍场进行时
                    viewHolders.tvLotsCountDown.init(0, endTime - nowTime, 1, new DownTextView.CouponDownInterface() {
                        @Override
                        public void runDown() {
                            viewHolders.tvItemBg.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void runText(long timer, int type) {

                        }
                    });
                }

                //商品点击事件
                RxView.clicks( viewHolders.llItem)
                        .throttleFirst(1, TimeUnit.SECONDS)
                        .subscribe(o -> {
                            if (viewHolders.tvItemBg.getVisibility() == View.VISIBLE) {
                                ToastUtil.show("本场次已经结束");
                            } else {
                                ProductDetailActivity.open(getContext(), data.id, "1");
                            }
                        }, throwable -> {
                        });
            }

            @Override
            protected int getDefaultLayout() {
                return R.layout.item_lots;
            }

            private Rect getScreenRect() {
                WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
                Point point = new Point();
                wm.getDefaultDisplay().getSize(point);
                return new Rect(0, 0, point.x, point.y);
            }

            public class ViewHolder extends EpoxyHolder {

                @BindView(R.id.image_lots_photo)
                ImageView imageLotsPhoto;
                @BindView(R.id.tv_lots_countDown)
                DownTextView tvLotsCountDown;
                @BindView(R.id.tv_lots_title)
                AppCompatTextView tvLotsTitle;
                @BindView(R.id.tv_lots_price)
                AppCompatTextView tvLotsPrice;
                @BindView(R.id.tv_lots_scprice)
                AppCompatTextView tvLotsScprice;
                @BindView(R.id.ll_item)
                LinearLayout llItem;
                @BindView(R.id.tv_item_bg)
                TextView tvItemBg;
                @BindView(R.id.lin_item_good)
                LinearLayout linItemGood;

                @Override
                protected void bindView(View itemView) {
                    ButterKnife.bind(this, itemView);
                }
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
